﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Windows.Forms;
using Ersur.ErsurDBTableAdapters;
using DevExpress.XtraEditors;
using Ersur;
using Karbel;
using Ersur.ErsurServices;

namespace Ersur.DevTeam
{
    public class Data
    {
        public static BindingSource bsProduct;
        public static BindingSource bsOrder;
        public static BindingSource bsOrderLines;

        static List<string> OriginalColumns;
        public static string[] ProductDetails = new string[] { "Article", "Count", "Composition", "MinDYELot", "Price"};
        public static Ersur.ErsurDBTableAdapters.TableAdapterManager TAM = new ErsurDBTableAdapters.TableAdapterManager();
        public static DataManager DataManager { get; set; }

        public static ErsurDB DB
        { get; set; }

        public static DataSet ExecuteDataSet(string SPName, params object[] parameters)
        {
            return DataManager.ExecuteDataSet(SPName, parameters);
        }

        public static void Init(string ConnectionString)
        {
            DataManager = new DataManager(ConnectionString);
             
            PropertyInfo[] props = Properties.Settings.Default.GetType().GetProperties();
            foreach (PropertyInfo prop in props)
            {
                SettingsProperty sett = Properties.Settings.Default.Properties[prop.Name];
                if (sett != null)
                {
                    Properties.Settings.Default[prop.Name]  = ConnectionString;
                }
            }

            DB = new ErsurDB();

            
            TAM.ProductTableAdapter = new ProductTableAdapter();
            TAM.OrderTableAdapter = new OrderTableAdapter();
            TAM.OrderLinesTableAdapter = new OrderLinesTableAdapter();
            TAM.ColourTableAdapter = new ColourTableAdapter();
            TAM.BallSizeTableAdapter = new BallSizeTableAdapter();
          
            TAM.ProductTableAdapter.Fill(DB.Product);
            TAM.OrderTableAdapter.Fill(DB.Order);
            TAM.OrderLinesTableAdapter.Fill(DB.OrderLines);
            TAM.ColourTableAdapter.Fill(DB.Colour);
            TAM.BallSizeTableAdapter.Fill(DB.BallSize);

            bsProduct = new BindingSource(Data.DB, "Product");
            bsOrder = new BindingSource(Data.DB, "Order");
            bsOrderLines  = new BindingSource(bsOrder, "FK_OrderLines_Order_OrderId");

            InitProduct();

            foreach (string col in ProductDetails)
                DB.OrderLines.Columns.Add(col, typeof(string));
        }

        private static void InitProduct( )
        { 
            OriginalColumns = new List<string>();
            foreach (DataColumn dc in DB.Product.Columns)
                OriginalColumns.Add(dc.ColumnName);


            DB.Product.Columns.Add("Select", typeof(bool));
            DB.Product.Columns.Add("Order", typeof(int));

            foreach (DataRow dr in DB.Product.Rows)
                dr["Select"] = false;

            DB.Product.TableNewRow += Product_TableNewRow;

            DB.Product.AcceptChanges();
        }

        private static void Product_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {
            e.Row["Select"] = false;
        }

        public static int SaveProduct(DataRow dr)
        {
            return Data.TAM.ProductTableAdapter.Update(dr);
        }

        public static void SaveOrder()
        {
            Data.TAM.OrderTableAdapter.Update(DB.Order);
            Data.TAM.OrderLinesTableAdapter.Update(DB.OrderLines);
        }
         
        public static void Save()
        {
            bsProduct.EndEdit();
            bsOrder.EndEdit();
            bsOrderLines.EndEdit();
            
            TAM.UpdateAll(Data.DB);
        }

        public static string Sync(DataRow[] drs)
        {
            string error = "";
            int lastIndex = 0;
            if (drs.Length > 0)
            {
                foreach (DataRow dr in drs)
                {
                    try
                    {
                        int orderId = int.Parse(dr["OrderId"].ToString());
                        DataTable dt = Data.DataManager.ExecuteDataTable("GetSyncData", orderId);
                        string xml = dt.Serialize();
                        ErsurServicesSoapClient service = new ErsurServicesSoapClient();
                        service.Sync("ers", Settings.TerminalNo, orderId, xml);

                        dr["SyncDate"] = DateTime.Now;
                        lastIndex++;
                    }
                    catch (ApplicationException ex)
                    {
                        error = ex.ToString();
                        break;
                    }
                }

                Data.Save();

            }
            
            return error + "sync is completed:" + lastIndex.ToString() + " item(s)";
        }

        public static string SendEmail(DataRow[] drs)
        {
            string error = "";
            int lastIndex = 0;
            if (drs.Length > 0)
            {
                foreach (DataRow dr in drs)
                {
                    try
                    {                         
                        int selectedOrderId = (int)dr["OrderId"];

                        string reference = "ERS-" + Settings.FairNo + "-" + Settings.TerminalNo + "-" + selectedOrderId.ToString().PadLeft(4, '0');
                        string FileName = reference + ".pdf";

                        string Brand = "";
                        if (dr["Brand"] != DBNull.Value && dr["Brand"] != null)
                            Brand = (string)dr["Brand"];

                        string Subject =  Settings.MailSubject.Replace("[BRAND]", Brand).Replace("[FAIR]", Settings.FairName);

                        DataSet dsReport = Data.DataManager.ExecuteDataSet("GetOrderReport", selectedOrderId, Settings.TerminalNo, Settings.FairNo);
                        OrderReport or = new OrderReport(dsReport);
                        string FilePath = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + "\\" + FileName;
                        or.ExportToPdf(FilePath);
                        Stream stream = new MemoryStream(File.ReadAllBytes(FilePath));

                        string To = "";
                        if (dr["Email"] != DBNull.Value && dr["Email"] != null)
                        {
                            To = (string)dr["Email"];

                            foreach (string email in To.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                            {
                                if (!email.IsValidEmail())
                                {
                                    XtraMessageBox.Show("e-mail address is invalid ! :" + email);
                                    return "";
                                }
                            }
                        }

                        string contact = "";
                        if (dr["Contact"] != DBNull.Value && dr["Contact"] != null)
                            contact = (string)dr["Contact"];

                        string[] tos = To.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        string[] contacts = contact.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                        if (tos.Length != contacts.Length)
                        {
                            XtraMessageBox.Show("Contact and email counts must be same !");
                            return "";
                        }
                           

                        List<MailMessage> mails = new List<MailMessage>();
                        for (int i = 0; i < tos.Length; i++)
                        {
                            MailMessage email = new MailMessage();
                            email.From = new MailAddress("fair@ersur.com.tr", "Ersur Textile");
                            email.Subject = Subject;
                            email.Body = Settings.MailBody.Replace("[NAME]", contacts[i].Trim());
                            email.IsBodyHtml = true;
                            email.To.Add(tos[i].Trim());
                            if (i == 0)
                                email.Bcc.Add("fair@ersur.com.tr");
                            email.Attachments.Add(new Attachment(stream, FileName));
                            mails.Add(email);
                        }

                        try
                        {
                            using (SmtpClient emailClient = new SmtpClient("85.105.182.185", 587))
                            {
                                emailClient.Credentials = new NetworkCredential("fair@ersur.com.tr", "fr2014fr");
                                foreach (MailMessage mail in mails)
                                    emailClient.Send(mail);

                                Data.DB.Order.Select("OrderId = " + selectedOrderId)[0]["eMailDate"] = DateTime.Now;
                            }
                        }
                        catch (Exception ex)
                        {
                            throw new ApplicationException("e-mails can not be send. Check the internet connection." + ex.ToString() + "...");
                        }
                        lastIndex++;
                    }
                    catch (ApplicationException ex)
                    {
                        error = ex.ToString();
                        break;
                    }
                }

                Data.Save();
                error = error + "e-mails are sent:" + lastIndex.ToString() + " item(s)";
            }
            return error;
        }
    }
}